
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;


import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.function.NormalDistributionFunction2D;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

public class ImageChart {

	private double xMinValue;
	private double xMaxValue;
	private String name;
	private HashMap<String, NormalDistributionFunction2D> functionMap;

	public ImageChart(String name) {
		this.name = name;
		xMinValue = 0;
		xMaxValue = 0;
		functionMap = new HashMap<String, NormalDistributionFunction2D>();
	}

	public void addRegionData(String name, double mean, double standarDeviation) {
		functionMap.put(name, new NormalDistributionFunction2D(mean,
				standarDeviation));
	}

	public ChartPanel getChartPanel() {
		XYSeriesCollection dataSet = createDataSet();
		JFreeChart chart = ChartFactory.createXYLineChart(
				name, "X", "Y", dataSet,
				PlotOrientation.VERTICAL, true, true, false);
		ChartPanel chartPanel = new ChartPanel(chart);
		chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
		return chartPanel;
	}

	private XYSeriesCollection createDataSet() {
		calculateBounds();

		double gap = ChartManager.GAP;
		XYSeriesCollection dataSet = new XYSeriesCollection();

		Collection<String> functions = functionMap.keySet();

		for (Iterator<String> iterator = functions.iterator(); iterator
				.hasNext();) {
			String name = (String) iterator.next();
			XYSeries serie = new XYSeries(name);
			NormalDistributionFunction2D function = functionMap.get(name);
			for (double i = xMinValue; i < xMaxValue; i = i + gap) {
				serie.add(i, function.getValue(i));
			}
			dataSet.addSeries(serie);
		}
		return dataSet;
	}

	private void calculateBounds() {
		double yMinValue = ChartManager.MIN_Y_VALUE;
		double gap = ChartManager.GAP;

		Collection<NormalDistributionFunction2D> functions = functionMap
				.values();

		for (Iterator<NormalDistributionFunction2D> iterator = functions
				.iterator(); iterator.hasNext();) {
			NormalDistributionFunction2D function = (NormalDistributionFunction2D) iterator
					.next();

			int i = 0;
			while (function.getValue(function.getMean() + gap * i) > yMinValue) {
				i++;
			}
			if (xMinValue > function.getMean() - gap * i)
				xMinValue = function.getMean() - gap * i;
			if (xMaxValue < function.getMean() + gap * i)
				xMaxValue = function.getMean() + gap * i;

		}
	}

	public String getName() {
		return this.name;
	}

}
